<template>
  <div class="px-4">
    <div class="my-4 w-full flex">
      <button class="mr-6 btn btn-primary" @click="toBack">返回</button>
      <input
        type="text"
        placeholder="请输入示例代码的标题"
        class="input input-bordered input-primary w-full"
        v-model="submitData.example_title"
      />
      <button class="ml-6 btn btn-primary" @click="submit">提交</button>
    </div>
    <div class="w-full">
      <textarea
        class="textarea textarea-primary w-full"
        placeholder="请输入示例代码的描述"
        v-model="submitData.example_desc"
      ></textarea>
      <label>
        <span class="btn mr-4 mb-4">选择封面图片</span>
        <input
          type="file"
          class="file-input file-input-bordered [&::file-selector-button]:hidden p-2.5"
          @change="handleFile"
          v-bind:src="submitData.file"
        />
      </label>
    </div>
    <div class="alert alert-info shadow-lg mb-4 w-72">
      <div>
        <svg
          xmlns="http://www.w3.org/2000/svg"
          fill="none"
          viewBox="0 0 24 24"
          class="stroke-current flex-shrink-0 w-6 h-6"
        >
          <path
            stroke-linecap="round"
            stroke-linejoin="round"
            stroke-width="2"
            d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"
          ></path>
        </svg>
        <span>你的示例代码在下方填入,根据右边展示内容确认无误后可上传审核</span>
      </div>
    </div>
    <div class="flex h-fit w-full pb-4">
      <div class="w-1/3" id="code-container" style="height: 900px"></div>
      <div class="w-2/3 border border-blue-400" id="code-result">
        <iframe
          class="w-full h-full"
          ref="frameDom"
          id="iframe"
          frameborder="0"
        ></iframe>
      </div>
    </div>
  </div>
</template>

<script setup>
import { useRoute, useRouter } from "vue-router";
import { nextTick, onMounted, ref } from "@vue/runtime-core";
import { EditorState, Compartment } from "@codemirror/state";
import { html } from "@codemirror/lang-html";
import { basicSetup } from "codemirror";
import { indentWithTab } from "@codemirror/commands";
import { EditorView, keymap } from "@codemirror/view";
import { dracula } from "@uiw/codemirror-theme-dracula";
import { exampleSubmit } from "@/api/example";
import { useStore } from "vuex";

/**
 * 示例代码相关
 */
let state = null;
let view = null;
let timer = null;
const frameDom = ref();
const runCode = function () {
  if (frameDom.value) {
    frameDom.value.srcdoc = view.state.doc.toString();
  }
};
const initDemo = function (doc) {
  const darkCodeTips = EditorView.theme({}, { dark: true });
  const languageConf = new Compartment();
  state = EditorState.create({
    extensions: [
      basicSetup,
      languageConf.of(html()),
      dracula,
      keymap.of([indentWithTab]),
      darkCodeTips,
      EditorView.updateListener.of((v) => {
        if (frameDom.value.srcdoc != v.view.state.doc.toString()) {
          if (timer) {
            clearTimeout(timer);
            timer = null;
          }
          timer = setTimeout(() => {
            runCode();
          }, 1000);
        }
      }),
    ],
    doc: doc,
  });
  view = new EditorView({
    state,
    parent: document.querySelector("#code-container"),
  });
  runCode();
};

/**
 *  按钮处理
 */
const store = useStore();
const submitData = ref({
  example_title: "",
  example_desc: "",
  file: null,
  // 留置后面处理
  user_id: store.state.qingUserInfo.id,
});
const router = useRouter();
const handleFile = function (e) {
  let file = e.target.files[0];
  submitData.value.file = file;
};

const toBack = function () {
  router.push("/userCenter");
};

const submit = function () {
  let formdata = new FormData()
  let current = submitData.value
  for(let i in current){
    formdata.append(i,current[i])
  }
  formdata.append('example_code',view.state.doc.toString())
  exampleSubmit(formdata).then(res=>{
    if(res.status == 200){
      router.push("/userCenter")
    }
  })
};

onMounted(() => {
  initDemo("666");
});
</script>

<style scoped>
/deep/.cm-editor {
  height: 900px;
}
</style>